package com.wtone.platform.gat.images.gat.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.wtone.platform.gat.images.gat.core.Constants;
import com.wtone.platform.gat.images.gat.core.Response;
import com.wtone.platform.gat.images.gat.digest.HttpRequestUtils;
import com.wtone.platform.gat.images.gat.entity.SubscribeDB;
import com.wtone.platform.gat.images.gat.entity.Subscribenotifications;
import com.wtone.platform.gat.images.gat.mapper.SubscribeMapper;
import com.wtone.platform.gat.images.gat.mapper.SubscribenotificationsMapper;
import com.wtone.platform.gat.images.gat.message.SubImageInfoCore;
import com.wtone.platform.gat.images.gat.model.*;
import com.wtone.platform.gat.images.gat.service.SubscribenotificPublicService;
import com.wtone.platform.gat.images.gat.utils.DateUtils;
import com.wtone.platform.gat.images.gat.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author: aiLin
 * @Date: 2020/9/29 12:05
 * @desc: 通知相关接口
 */
@Slf4j
@Service
public class SubscribenotificPublicServiceImpl implements SubscribenotificPublicService {


    @Autowired
    HttpServletRequest request;

    @Autowired
    private SubscribeMapper subscribeMapper;

    //订阅通知数据层
    @Autowired
    private SubscribenotificationsMapper subscribenotificationsMapper;

    @Value("${img.imgPath}")
    private String IMGPATH;


    /***
     * 发布接口 （推送消息给上级） 内部调用与接收
     *
     * 推送时候要获取上级 User-Identify 注册获取
     *
     * 接收时候要验证下级 User-Identify 校验
     *
     * @param subscribeNotific 通知内容 测试
     */
    private static final String PARAM = "";
    private static final String USERNAME = "admin";
    private static final String PASSWORD = "admin";

    @Override
    public ResponseStatusListModeObject subscribeNotifications(SubscribeNotificationListObject subscribeNotific) {
        String reqUrl = "/VIID/SubscribeNotifications";
        List<ResponseStatus> resp3 = new ArrayList<ResponseStatus>();
        //视图库编号
        String subscribeID = request.getHeader(Constants.REQTOKEN);
        System.out.println(" ");
        log.info("8066发送订阅消息：subscribeNotific：{}", String.valueOf(subscribeNotific).substring(0,300));
        //订阅标识
        if(subscribeNotific==null){
            return Response.error(subscribeID,reqUrl, Constants.JSONRES);
        }
        //List<Subscribe> subscribeAlls = redisUtils.getSubscribeAlls();
        SubscribeDB subscribeDB = new SubscribeDB();
        List<SubscribeDB> subscribeDBS = subscribeMapper.selectSubscribeObj(subscribeDB);
        log.info("订阅列表subscribe:{}",subscribeDBS);

        if(subscribeDBS==null || subscribeDBS.size()<=0){
            return Response.error(subscribeID,reqUrl,Constants.OPERATION);
        }

        for(int i=0;i<subscribeDBS.size();i++){
            System.out.println(" ");
            ResponseStatus r = new ResponseStatus();
            SubscribeDB subscribe = subscribeDBS.get(i);
            String subscribeId = subscribe.getSubscribeid();
            if(!("0").equals(subscribe.getSubscribestatus())){//状态：订阅中
                r = Response.getResponError(subscribeId, reqUrl,"订阅者："+subscribeId+"状态异常,推送失败！");
                resp3.add(r);
                continue;
            }
            Date beginTime = DateUtils.dateTime(DateUtils.YYYYMMDDHHMMSS, subscribe.getBegintime());
            Date endTime = DateUtils.dateTime(DateUtils.YYYYMMDDHHMMSS, subscribe.getEndTime());
            long endTimes = endTime.getTime();
            Date nowTime = DateUtils.dateTime(DateUtils.YYYY_MM_DD_HH_MM_SS,DateUtils.getTime());
            long time = nowTime.getTime();
            if(endTimes<time){//状态：订阅中，时间超期，也取消推送
                r = Response.getResponError(subscribeId, reqUrl,"订阅者:"+subscribeId+",时间到期推送失败！");
                resp3.add(r);
                continue;
            }
            Gson gson = new Gson();
            String params = gson.toJson(Response.object2UpperCase(subscribeNotific));  //转换json数据
            log.info("推送给订阅者{}：消息：{}",subscribeId,String.valueOf(params).substring(0,300));
            try {
                List<SubImageInfo> imgSize = new ArrayList<SubImageInfo>();
                try {
                    MotorVehicle motorVehicle = subscribeNotific.getSubscribeNotificationObject().getSubscribeNotifications().get(0).getMotorVehicleObjectList().getMotorVehicles().get(0);
                    imgSize = motorVehicle.getSubImageInfoList().getSubImageInfo();
                }catch (NullPointerException e){
                    imgSize = subscribeNotific.getSubscribeNotificationObject().getSubscribeNotifications().get(0).getFaceObjectList().getFaceObject().getFaceList().get(0).getSubImageInfoList().getSubImageInfo();
                }
                if(imgSize.size()>=1){
                    List<SubImageInfo> finalImgSize = imgSize;
                    new Thread(() -> {
                        SubImageInfoCore.getSubImageInfo(finalImgSize);
                    }).start();
                    //HttpResponse httpResponse = HttpRequest.post(subscribe.getReceiveAddr()).body(params, "application/json").timeout(3 * 1000).execute();
                    String result = HttpRequestUtils.sendPost(subscribe.getReceiveaddr(), PARAM, USERNAME, PASSWORD, params, "json",subscribeId);
                    JSONObject faresult = JSONObject.parseObject(result);
                    Integer status = 0;
                    if(result.contains("errCode")){
                        status = (Integer)faresult.get("errCode");
                    }else if(result.contains("正常")){
                        status = 200;
                    }
                    log.info("推送状态:{}",status);
                    System.out.println(" ");
                    if(status!=200){
                        r = Response.getResponError("异常："+subscribeId, reqUrl,"推送失败！");
                    }else{
                        r = Response.getResponOk(subscribeId, reqUrl);
                    }
                }else{
                    r = Response.getResponError("图片信息不存在："+subscribeId, reqUrl,"推送失败！");
                }
            }catch (Exception e){
                if(e.toString().contains("connect timed out")){
                    log.info("推送状态:{},异常消息：{}",500,subscribeId+" connect timed out");
                    r = Response.getResponError(subscribeId, reqUrl,"异常："+subscribeId+" connect timed out");
                }else{
                    log.info("推送状态:{},异常消息：{}",500,subscribeId+" "+e.toString());
                    r = Response.getResponError(subscribeId, reqUrl,"异常："+subscribeId+" "+e.toString());
                }
            }
            resp3.add(r);
        }
        //异步保存推送消息记录
        new Thread(() -> {
            saveSubscribeNotificationDB(subscribeNotific,subscribeDBS);
        }).start();
        return Response.ok(resp3);
    }

    /***
     * 查询任务接口
     * @return
     */
    @Override
    public SubscribeNotificationListObject selectSubscribeNotifications(String NotificationID,String SubscribeID,String Title,String executeoperation) {
        Subscribenotifications sub = new Subscribenotifications();
        sub.setNotificationid(NotificationID!=null ? NotificationID:"");
        sub.setSubscribeid(SubscribeID!=null ? SubscribeID : "");
        sub.setTitle(Title!=null ? Title : "");
        sub.setExecuteoperation(executeoperation!=null ? executeoperation : "");
        SubscribeNotificationListObject resultObject = new SubscribeNotificationListObject();
        List<Subscribenotifications> subscribenotifications = subscribenotificationsMapper.selectSubscribenotificationsList(sub);
        if(subscribenotifications!=null && subscribenotifications.size()>0){
            Subscribenotifications result = subscribenotifications.get(0);
            String json = result.getJson();
            //下面是把拿到的json字符串转成 json对象
            JSONObject jsStr = JSONObject.parseObject(json);
            /**
             * json对象转换成java对象
             */
           resultObject = (SubscribeNotificationListObject) JSONObject.toJavaObject(jsStr,SubscribeNotificationListObject.class);
        }
        return resultObject;
    }

    /***
     * 订阅删除
     * @param IDList
     * @return
     */
    @Override
    public ResponseStatusListModeObject deleteSubscribeNotifications(String IDList) {
        String reqUrl = "/VIID/SubscribeNotifications";
        List<ResponseStatus> resp3 = new ArrayList<ResponseStatus>();
        ResponseStatus r = new ResponseStatus();
        if(StringUtils.isEmpty(IDList)){
            r = Response.getResponError(IDList, reqUrl,"通知id不存在，删除失败");
            resp3.add(r);
        }
        if(!IDList.contains(",")){
            IDList = IDList+",";
        }
        if(IDList.contains(",")){
            String[] ids = IDList.split(",");
            for(int i=0;i<ids.length;i++){
                int mark = subscribenotificationsMapper.deleteSubscribenotificationsById("",ids[i]);
                if(mark>=1){
                    r = Response.getResponOk(IDList, reqUrl,"通知id:"+ids[i]+"，删除成功");
                }else{
                    r = Response.getResponError(IDList, reqUrl,"通知id:"+ids[i]+"，不存在，删除失败");
                }
                resp3.add(r);
            }
        }
        return Response.ok(resp3);
    }

    /**
     * 异步保存推送消息记录
     * @param subscribeDBS 多条消息记录
     */

    public void saveSubscribeNotificationDB(SubscribeNotificationListObject subscribeNotific,List<SubscribeDB> subscribeDBS){

        if(subscribeDBS==null || subscribeDBS.size()<=0){
            log.warn("消息对象为空，保存异常");
            return;
        }
        for(int k=0;k<subscribeDBS.size();k++){
            SubscribeDB subscribeDB = subscribeDBS.get(k);
            List<SubscribeNotification> subscribeNotifications = subscribeNotific.getSubscribeNotificationObject().getSubscribeNotifications();
            if(subscribeNotifications==null ||subscribeNotifications.size()<=0){
                log.warn("消息对象为空，保存异常");
                return;
            }
            for(int i=0;i<subscribeNotifications.size();i++){
                SubscribeNotification s = subscribeNotifications.get(i);
                Subscribenotifications sub = new Subscribenotifications();
                sub.setJson(String.valueOf(JSON.toJSON(subscribeNotific)));
                if(s==null){
                    continue;
                }
                sub.setApsobjectlist(s.getAPSObjectList()!=null ? s.getAPSObjectList() : "");
                sub.setApsstatusobjectlist(s.getAPSStatusObjectList()!=null ? s.getAPSStatusObjectList() : "");
                sub.setCaseobjectlist(s.getCaseObjectList()!=null ?s.getCaseObjectList() : "");
                sub.setCreateBy("admin");
                sub.setCreateTime(DateUtils.getNowDate());
                sub.setDataclasstabobjectlist(s.getDataClassTabObjectList()!=null ? s.getDataClassTabObjectList() : "");
                sub.setDevicelist(s.getDeviceList()!=null ? s.getDeviceList() : "");
                sub.setExecuteoperation(s.getExecuteOperation()!=0 ? String.valueOf(s.getExecuteOperation()) : "0");
                sub.setInfoids(s.getInfoIDs()!=null ? s.getInfoIDs() : "");
                FaceListObject faceObjectList = s.getFaceObjectList();
                sub.setFaceobjectlist(String.valueOf(faceObjectList));
                sub.setLane(s.getLane()!=null ? s.getLane() : "");
                sub.setMotorvehicleobjectlist(s.getMotorVehicleObjectList()!=null ? String.valueOf(s.getMotorVehicleObjectList()) : "");
                sub.setNonmotorvehicleobjectlist(s.getNonMotorVehicleObjectList()!=null ? s.getNonMotorVehicleObjectList() :"");
                sub.setTriggertime(DateUtils.dateTimeNow());
                sub.setThingobjectlist(s.getThingObjectList()!=null ? s.getThingObjectList() : "");
                sub.setPersonobjectlist(s.getPersonObjectList()!=null ? s.getPersonObjectList() : "");
                sub.setDevicestatuslist(s.getDeviceStatusList()!=null ? s.getDataClassTabObjectList() : "");
                sub.setSceneobjectlist(s.getSceneObjectList()!=null ? s.getSceneObjectList(): "");
                sub.setNotificationid(s.getNotificationID()!=null ? s.getNotificationID() : "");
                sub.setSubscribeid(subscribeDB.getSubscribeid()!=null ? subscribeDB.getSubscribeid() : "");
                sub.setTitle(s.getTitle()!=null ? s.getTitle() : "");
                sub.setTollgate(s.getTollgate()!=null ? s.getTollgate() : "");
                try {
                    int mark = subscribenotificationsMapper.insertSubscribenotifications(sub);
                    if(mark>=1){
                        log.info("订阅消息：{}，记录成功",s.getNotificationID());
                    }else{
                        log.info("订阅消息：{}，记录失败",s.getNotificationID());
                    }
                }catch (Exception e){
                    if(String.valueOf(e).contains("唯一")){
                        log.error("消息已存在，不重新记录：{}");
                    }
                }
            }
        }
    }
}
